package com.aaron.demo1.common.action;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author liurong
 * @date 2021/7/9 17:51
 */
@RestController
@RequestMapping("/demo1/test")
public class Demo1Action {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //http://doc.redisfans.com/ redis命令
    //redis命令与Redisson的对应关系  http://www.manongjc.com/article/53404.html
    /*
        String: set -- RBucket.set()


     */

    @GetMapping
    public String test() {
        RBucket<Object> bucket01 = redissonClient.getBucket("bucket01");
        bucket01.set("key01", 5, TimeUnit.MINUTES);
        return "demo01 redisson测试1";
    }


    public void test02(){

//        redissonClient.getLock()
    }

    @PostMapping
    public String deductStock() {

        int stock = Integer.valueOf(stringRedisTemplate.opsForValue().get("stock"));
        HashMap<String, String> response = new HashMap<>();
        String message = "";
        if (stock > 0) {
            int realStock = stock - 1;
            stringRedisTemplate.opsForValue().set("stock", realStock + "");
//            stringRedisTemplate.opsForValue().decrement("stock", -1);
            message = "成功，库存剩余：" + realStock;
            System.out.println(message);
        } else {
            message = "库存不足";
            System.out.println(message);
        }

        return message;
    }

    @GetMapping("deductStock2")
    public String deduct2(){
        try{
            Boolean isSuccessSet = stringRedisTemplate.opsForValue().setIfAbsent("lock", "aaron");
            stringRedisTemplate.expire("lock", 20, TimeUnit.SECONDS);
            //上面两句可以在一起执行的api也有的
            stringRedisTemplate.opsForValue().set("lock", "aaron", 20, TimeUnit.SECONDS);//作为一个原子代码块一起执行
            //同时成功同时失败

            if (!isSuccessSet) {
                return "error";
            }

        }finally {
            stringRedisTemplate.delete("lock");
        } //不能写在catch里面（catch有Exception、Throwable）
        return null;
    }

}

